package com.wtpaint.leetcode.查找表;

import java.util.Arrays;

public class ThreeSumClosest16 {


    public static int threeSumClosest(int[] nums, int target) {

        Arrays.sort(nums);
        int closest = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length - 2; i++) {
            int j = i + 1;
            int k = nums.length - 1;

            while (j < k) {
                int threeNum = nums[i] + nums[j] + nums[k];
                if (Math.abs(threeNum - target) < Math.abs(closest - target)) {
                    closest = threeNum;
                }

                if (threeNum < target) {
                    while (j < k && nums[j] == nums[j + 1]) j++;
                    j++;
                } else if (threeNum > target) {
                    while (j < k && nums[k] == nums[k - 1]) k--;
                    k--;
                } else {
                    return target;
                }
            }

        }

        return closest;
    }
    //[1,2,4,8,16,32,64,128]
    //82

    public static void main(String[] args) {
//        System.out.println("  " + threeSumClosest(new int[]{-1, 2, 1, -4}, 1));
        System.out.println("  " + threeSumClosest(new int[]{1,2,4,8,16,32,64,128}, 82));
    }
}
